<?php
/**
* Copyright (c) 2002-2007 BioWare Corp.
* http://www.bigdaddymonitor.org
*
* This file is part of the BigDaddy Monitoring
* program. It is free software distributed under
* the terms of the BSD License. It is ditributed
* in the hopes that it will be useful, but
* WITHOUT ANY WARRANTY; without event the implied
* warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE.
*
* The BSD License is available from:
* http://www.opensource.org/licenses/bsd-license.php
**/
/**
 * BigDaddy Class: User Administration
 * @author Duleepa Wijayawardhana <dups@bioware.com>
 * @version Mon Oct 02 12:04:56 2006
 *
 * Methods to manage users on BigDaddy
 */
class UserAdmin
{
    /**
     * @var obj Contains the role class
     */
    private $Role;
    /**
     * @var obj Contains the audit class
     */
    private $Audit;
    /**
     * @var string Currently Logged in user
     */
    private $sLoggedInUsername;
    
    /**
     * @var Action to view user admin pages
     */
    private $sAction_ViewUserAdmin = "view-user-admin";
    private $sAction_AddUsers = "create-new-user";
    private $sAction_EditUsers = "edit-users";
    private $sAction_DeleteUser = "delete-users";
    
    /**
     * @var string default password for setting a new account
     */
    private $sDefaultPassword = "Password1234!";
    
    
    
    /**
     * Constructor
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 12:06:08 2006
     */
    public function __construct()
    {
        $this->Role = $GLOBALS["Role"];
        $this->sLoggedInUsername = LOGGEDIN_USERNAME;
        $this->Audit = $GLOBALS["Audit"];
    }
    /**
     * IsAllowed
     *
     * Checks Methods to see if the user has access to run a function
     * 
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 14:25:04 2006
     * @param string $sMethod
     * @param string $sUsername
     * @return bool
     */
    private function IsAllowed ($sMethod, $sUsername = NULL)
    {
        if ($sUsername == NULL)
        {
            $sUsername = $this->sLoggedInUsername;
        }
        
        $sMethod = str_replace(__CLASS__."::", "", $sMethod);
        $sMethod = strtolower($sMethod);
        
        $aAllowedActions = array (
        "getusers" => $this->sAction_ViewUserAdmin,
        "getuserinfobyusername" => $this->sAction_ViewUserAdmin,
        "setuser" => $this->sAction_ViewUserAdmin,
        "setactivestatebyusername" => $this->sAction_ViewUserAdmin,
        "resetpassword" => $this->sAction_ViewUserAdmin,
	"setpassword" => $this->sAction_ViewUserAdmin,
        );
        
        if ($this->Role->IsGlobalActionAvailableToUser($aAllowedActions[$sMethod], $sUsername))
        {
            return true;
        }
        
        return false;
        
    }
    
    /**
     * GetUsers
     *
     * Returns all users in the user table for BD
     * 
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 12:09:24 2006
     * @return array
     */
    public function GetUsers ()
    {
        if (!$this->IsAllowed(__METHOD__))
        {
            return;
        }
            
        
        $sql = "SELECT *
            FROM users
            ORDER BY lastActive DESC, username ASC";
        $aResult = db_fetch_array(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
    }
    /**
     * GetUserInfoByUsername
     *
     * Returns a particular user
     * 
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 12:09:24 2006
     * @param string $sUsername
     * @return array
     */
    public function GetUserInfoByUsername ($sUsername)
    {
        if (!$this->IsAllowed(__METHOD__))
        {
            return;
        }
        
        if ($sUsername == "")
        {
            return;
        }
        
        $sql = "SELECT *
            FROM users
            WHERE username = '".$sUsername."'";
        $aResult = db_fetch_result(db_query($sql));
        
        if (is_array($aResult))
        {
            return $aResult;
        }
    }
    /**
     * SetActiveStateByUsername
     * Sets the active state on or off by username
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 15:28:11 2006
     * @param string $sUsername
     * @param string $sState (activate/deactivate)
     * @return string
     */
    public function SetActiveStateByUsername($sUsername, $sState)
    {
        if (!$this->IsAllowed(__METHOD__))
        {
            return "Not Allowed";
        }
        
        switch ($sState)
        {
            case "activate":
                $bActive = 1;
                break;
            case "deactivate":
                $bActive = 0;
                break;
            case "":
            default:
                return;
        }
        
        $sql = "UPDATE users
            SET active = '".$bActive."'
            WHERE username = '".$sUsername."'";
        db_query($sql);
     
        $aInfo["usernameAffected"] = $sUsername;
        $aInfo["action"] = "Set-Active-Status";
        $aInfo["comment"] = "$sUsername active status was set to $bActive";
        $this->Audit->SetAudit($aInfo, "useradmin");
        
        return "Updated Active State for ".$sUsername;
    }
    /**
     * SetUser
     * Sets information for a user
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 15:36:59 2006
     * @param array $aInfo
     * @param string $sUsername
     * @return string
     */
    public function SetUser ($aInfo, $sUsername)
    {
        if (!$this->IsAllowed(__METHOD__))
        {
            return "Not Allowed";
        }
        
        if (!is_array($aInfo))
        {
            return "No Array";
        }
        
        //Check to see if this user already exists
        $sql = "SELECT COUNT(*) as count
            FROM users
            WHERE username = '".$sUsername."'";
        $aResult  = db_fetch_result(db_query($sql));
        
        if ($aResult["count"] > 0)
        {
            $bDoUpdate = true;
        }
        
        if ($bDoUpdate)
        {
            $sqlSet = "UPDATE users SET ";
        }
        else
        {
            $sqlSet = "INSERT INTO users SET
            username = '".$sUsername."',
            password = '".md5($this->sDefaultPassword)."',";

        }
        
        $sql = $sqlSet."
            firstname = '".$aInfo["firstname"]."',
            lastname = '".$aInfo["lastname"]."',
            fullname = '".$aInfo["firstname"]." ".$aInfo["lastname"]."',
            cn = '".$aInfo["firstname"]." ".$aInfo["lastname"]."',
            position = '".$aInfo["position"]."',
            location = '".$aInfo["location"]."' ";
        
        if ($bDoUpdate)
        {
            $sql.=" WHERE username = '".$sUsername."'";
        }
        
        $nAffectedRows = db_query($sql, array("getAffectedRows" => 1));
        
        if ($nAffectedRows > 0)
        {
            $aAuditInfo["usernameAffected"] = $sUsername;
            $aAuditInfo["action"] = "Set-User";
            
            if ($bDoUpdate)
            {
                $aAuditInfo["comment"] = "$sUsername information was changed Information entered: ".print_r($aInfo, true);
                $sReturn = "Updated";
            }
            else
            {
                $aAuditInfo["comment"] = "$sUsername was inserted";
                $sReturn = "Inserted";
            }
                
            $this->Audit->SetAudit($aAuditInfo, "useradmin");
            return $sReturn;
        }
        
        return "Unknown Error check DB (or no changes were made): $sql";
    }
    /**
     * SetPassword
     * Administrator setting of someone's password
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 15:56:56 2006
     * @param string $sPassword
     * @param string $sConfirm
     * @param string $sUsername
     * @return string Error
     */
    public function SetPassword ($sPassword, $sConfirm, $sUsername)
    {
	if ( ! $sUsername ) {
		return "No username";
	}
        if (!$this->IsAllowed(__METHOD__))
        {
            return "SetPassword not allowed";
        }
        
        $sPassword = stripslashes($sPassword);
        $sConfirm = stripslashes($sConfirm);
        
        if (!$this->CheckPasswordSyntax("checkempty", $sPassword))
        {
            return "Password Empty";
        }
        
        if (!$this->CheckPasswordSyntax("mismatchstrings", $sPassword,$sConfirm))
        {
            return "Password  and Confirmation Do Not Match !$sPassword!$sConfirm!";
        }
        
        if (!$this->CheckPasswordSyntax("checklength", $sPassword))
        {
            return "Password too short";
        }
        
        if (!$this->CheckPasswordSyntax("stringcheck", $sPassword))
        {
            return "Password should contain characters from two of the following groups, alpha numeric, numbers and special characters";
        }
        
        $sql = "UPDATE users SET
            password = '".md5($sPassword)."'
            WHERE username = '".$sUsername."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => 1));
        
        if ($nAffectedRows > 0)
        {
            $aAuditInfo["usernameAffected"] = $sUsername;
            $aAuditInfo["action"] = "Set-Password";
            $aAuditInfo["comment"] = "Administrator changed password for $sUsername";
               
            $this->Audit->SetAudit($aAuditInfo, "useradmin");
            
            return "Password Changed";
        }
        
        return "There was a problem setting the password $sql !$sUsername!";

    }
    /**
     * CheckPasswordSyntax
     * Check for password syntax
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 16:43:11 2006
     * @param string $sTest
     * @param string $sPassword
     * @param string $sOtherString usually a comparison string
     * @return bool
     */
    private function CheckPasswordSyntax($sTest, $sPassword, $sOtherString=NULL)
    {

        switch ($sTest)
        {
            case "checkempty":
                if ($sPassword == "" || !$sPassword)
                {
                    return false;
                }
            break;
    
            case "matchstrings":
                if ($sPassword == $sOtherString)
                {
                    return false;
                }
            break;
    
            case "mismatchstrings":
                if ($sPassword != $sOtherString)
                {
                    return false;
                }
            break;
    
            case "checklength":
                $nLength=strlen($sPassword);
                if ($nLength<7)
                {
                    return false;
                }
            break;

            case "stringcheck":
            if (!preg_match("#[0-9]#", $sPassword) || !preg_match("#[A-Za-z]#", $sPassword))
            {
                return false;
            }
            break;
    
        }
        return true;
    }
    /**
     * ResetPassword
     * Resets a password to the default password
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Tue Oct 03 11:43:40 2006
     * @param string $sUsername
     * @return string
     */
    public function ResetPassword ($sUsername)
    {
        if (!$this->IsAllowed(__METHOD__))
        {
            return "Not Allowed";
        }
        
        $sql = "UPDATE users SET
        password = '".md5($this->sDefaultPassword)."'
        WHERE username = '".$sUsername."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => 1));
        
        if ($nAffectedRows > 0)
        {
            $aAuditInfo["usernameAffected"] = $sUsername;
            $aAuditInfo["action"] = "Reset-Password";
            $aAuditInfo["comment"] = "Administrator reset password for $sUsername";
               
            $this->Audit->SetAudit($aAuditInfo, "useradmin");
            
            return "Password reset";
        }
        
        return "Unknown Error: $sql";
    }
    /**
     * SetMyPassword
     * Administrator setting of someone's password
     * @author Duleepa Wijayawardhana <dups@bioware.com>
     * @version Mon Oct 02 15:56:56 2006
     * @param string $sPassword
     * @param string $sConfirm
     * @param string $sUsername
     * @return string Error
     */
    public function SetMyPassword ($sPassword, $sConfirm)
    {
       
        $sPassword = stripslashes($sPassword);
        $sConfirm = stripslashes($sConfirm);
        
        if (!$this->CheckPasswordSyntax("checkempty", $sPassword))
        {
            return "Password Empty";
        }
        
        if (!$this->CheckPasswordSyntax("mismatchstrings", $sPassword, $sConfirm))
        {
            return "Password  and Confirmation Do Not Match";
        }
        
        if (!$this->CheckPasswordSyntax("checklength", $sPassword))
        {
            return "Password too short";
        }
        
        if (!$this->CheckPasswordSyntax("stringcheck", $sPassword))
        {
            return "Password should contain characters from two of the following groups, alpha numeric, numbers and special characters";
        }
        
        $sql = "UPDATE users SET
            password = '".md5($sPassword)."'
            WHERE username = '".$this->sLoggedInUsername."'";
        $nAffectedRows = db_query($sql, array("getAffectedRows" => 1));
        
        if ($nAffectedRows > 0)
        {
            return "Password Changed";
        }
        
        return "There was a problem setting the password";

    }
    
    
}



?>
